import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { UnloginException } from 'src/filter/unlogin.filter';

@Injectable()
export class PermissionGuard implements CanActivate {
  @Inject()
  private readonly reflector: Reflector;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();

    // 没登陆就不用判断权限
    if (!request.user) return true;

    const permissions = request.user.permissions;

    const requirePermission = this.reflector.getAllAndOverride(
      'require-permission',
      [context.getHandler(), context.getClass()],
    );

    if (!requirePermission) return true;

    // &&
    const hasPermission = requirePermission.every((permission) =>
      permissions.includes(permission),
    );

    if (hasPermission) return true;
    throw new UnloginException('没有权限访问该接口');
  }
}
